<script lang="ts" setup>
import { ref, watch } from 'vue'
import { DateModelType } from 'element-plus'
import { computed } from 'vue'
import { formatDateTime } from '@/utils'
type ModelDateType = string | number | Date | [DateModelType, DateModelType]
const props = defineProps<{
  modelValue: ModelDateType
}>()
const internalDateRange = ref<ModelDateType>('')
// 抛出事件
const emits = defineEmits(['update:modelValue', 'change'])

const shortCut = ref<string>('')
const handleShortCutChange = (shortcut: string): [Date, Date] | [string, string] => {
  const end: DateModelType = new Date()
  const start: DateModelType = new Date()
  switch (shortcut) {
    case '':
      return ['', '']
    case 'today':
      start.setDate(end.getDate() - 1)
      break
    case 'last7':
      start.setDate(end.getDate() - 6)
      break
    case 'last30':
      start.setDate(end.getDate() - 29)
      break
    default:
      // 如果传递的shortcut不匹配任何案例，则可以选择返回空字符串数组
      return ['', '']
  }
  return [formatDateTime(start), formatDateTime(end)]
}
const computedShortCutsChange = computed(() => handleShortCutChange(shortCut.value))

watch(
  shortCut,
  () => {
    internalDateRange.value = computedShortCutsChange.value
    emits('update:modelValue', internalDateRange.value)
  },
  { immediate: true }
)
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue) {
      internalDateRange.value = newValue
    }
  },
  { immediate: true }
)
</script>

<template>
  <el-date-picker
    v-model="internalDateRange"
    type="datetimerange"
    value-format="YYYY-MM-DD HH:mm:ss"
    format="YYYY-MM-DD HH:mm:ss"
    range-separator="至"
    start-placeholder="请选择"
    end-placeholder="请选择"
  />
  <el-radio-group v-model="shortCut" ml-20>
    <el-radio-button value="today" label="今日" />
    <el-radio-button value="last7" label="近7天" />
    <el-radio-button value="last30" label="近30天" />
  </el-radio-group>
</template>

<style scoped></style>
